New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

ts-railway

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-railway

ROP flavoured Result & AsyncResult types

  • 6.1.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
415
increased by18.57%
Maintainers
1
Weekly downloads
 
Created
Source

ts-railway

npm build publish codecov Type Coverage Libraries.io dependency status for latest release bundlejs npm

ROP flavoured Result & AsyncResult types. Based on Railway oriented programming article by Scott Wlaschin.

Getting started

$ npm i ts-railway

Overview

Main types


Functions

All mapping functions have at least two overloaded signatures - common (transform, result) => new_result and curried (transform) => (result) => new_result. Curried form is intended to be used with some piping function (e.g. pipe-ts).

ResultAsyncResult
success↗️🚫
failure↗️🚫
map↗️↗️
mapError↗️↗️
flatMap↗️↗️
flatMapError↗️↗️
mapAsync🚫↗️
mapAsyncError🚫↗️
match↗️↗️
combine↗️↗️

Usage

Avoiding 'pyramid of doom'

Composing several functions with multiple arguments can be cumbersome and will lead to 'pyramid of doom' style of code:

const div = (a: number, b: number) /*: Result<number, 'div by zero'> */ =>
  b === 0 ? Result.failure('div by zero' as const) : Result.success(a / b)

const result = Result.map(
  (x: string) => [...x].reverse().join(''),
  Result.map(
    (x: number) => `${x}`,
    Result.map(
      (x: number) => x + 234,
      Result.mapError(
        (x: 'div by zero') => ({ divError: x } as const),
        Result.map((x) => x * 2, div(500, 1))
      )
    )
  )
)

expect(result).toEqual({
  tag: 'success',
  success: '4321'
})

This can be easily avoided when using curried forms of functions with a piping function:

import { pipeWith } from 'pipe-ts'

const result = pipeWith(
  div(500, 1),
  Result.mapError((x) => ({ divError: x } as const)),
  Result.map((x) => x * 2),
  Result.map((x) => x + 234),
  Result.map((x) => `${x}`),
  Result.map((x) => [...x].reverse().join(''))
)

expect(result).toEqual<typeof result>({
  tag: 'success',
  success: '4321'
})

Programming style

There are certain catches of railway oriented programming. Most of them are matter of program design quality. But in the context of TypeScript language, the most serious problem is the ability to completely discard the result of a function call (TypeScript/#8240, TypeScript/#8584). For example, in the following snippet possible parsing error will be discarded:

declare const obj: {
  parse: <T>(json: string) => Result<T, Error>
}

function foo() {
  obj.parse('][') // Result is discarded!
}

foo()

More sneaky error:

declare function updateUser(info: { name: string }): AsyncResult<undefined, Error>

declare const MyButton: {
  onClick: () => void
}

MyButton.onClick(
  () => updateUser({ name: 'username' }) // AsyncResult is covered with void and discarded!
)

These kind of problems can be minimized by using proper project configuration: setting "strict": true in tsconfig, prohibiting expression statements with functional/no-expression-statement rule from eslint-plugin-functional and banning void type with @typescript-eslint/ban-types rule from @typescript-eslint/eslint-plugin. tsconfig.json and .eslintrc files from this project could be used as a starting point.


Exception handling

ts-railway is intended to handle only domain errors and doesn't catch thrown exceptions and unhandled promise rejections. The common scenario to deal with exceptions is to catch them globally, log somehow and then decide whether to prevent an exception by fixing/changing the program or to convert that exception to domain error:

const errorHandler: OnErrorEventHandlerNonNull = (event) => {
  MyLoggingService.log(event)
}

window.onerror = errorHandler
window.onunhandledrejection = errorHandler

'Ecosystem'

Some packages compatible with ts-railway:

  • spectypes - fast, compiled, eval-free data validator/transformer
  • fetchmap - non-throwing fetch wrapper
  • ts-elmish - elmish architecture in typescript

Keywords

FAQs

Package last updated on 14 Aug 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc